package com.ziyia.providertest;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private Button insert, query, delete;
    private final String AUTHORITY = "com.ziyia.databasetest.provider";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();

        insert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Uri uri = Uri.parse("content://" + AUTHORITY + "/Book");
                ContentValues contentValues = new ContentValues();
                contentValues.put("name", "年少有为最新加添");
                contentValues.put("author", "嘿嘿");
                contentValues.put("pages", 400);
                contentValues.put("price", 1.5);
                Uri newUri = getContentResolver().insert(uri, contentValues);
            }
        });


        query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Uri uri = Uri.parse("content://" + AUTHORITY + "/Book");
                Cursor query = getContentResolver().query(uri, null, null, null, null);

                if (query != null) {
                    while (query.moveToNext()) {
                        String name = query.getString(query.getColumnIndex("name"));
                        Log.d("query", name);
                    }
                }

            }
        });

        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Uri uri = Uri.parse("content://" + AUTHORITY + "/book");
                getContentResolver().delete(uri, null, null);
            }
        });
    }


    private void init() {
        insert = findViewById(R.id.insert);
        query = findViewById(R.id.query);
        delete = findViewById(R.id.delete);
    }
}